package com.peanut.baby.util;

import com.peanut.devlibrary.security.MD5;

import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.FormBody;

/**
 * Created by anonymouslystudio on 2017/7/13.
 */

public class SignTools {
    public static String MD5_PREFIX = "hsby567*&%";

    private static MapKeyComparator mapKeyComparator = new MapKeyComparator();


    public static String createSign(FormBody body) {

        Map<String, Object> resultMap = sortMapByKey(formBodyToMap(body));    //按Key进行排序
        String originalCode = MD5_PREFIX;
        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            originalCode += entry.getValue();
        }
        return MD5.str2MD5(originalCode);
    }

    public static Map<String, Object> formBodyToMap(FormBody body) {
        if (body == null) {
            return null;
        }
        Map<String, Object> sortMap = new  HashMap<String,Object>();
        for(int i=0;i<body.size();i++){
            sortMap.put(body.name(i),body.value(i));
        }
        return sortMap;
    }


    /**
     *
     * @param params
     * @return
     */
    public static String createSign(HashMap<String, Object> params) {
        Map<String, Object> resultMap = sortMapByKey(params);    //按Key进行排序
        String originalCode = MD5_PREFIX;
        for (Map.Entry<String, Object> entry : resultMap.entrySet()) {
            originalCode += entry.getValue();
        }
        return MD5.str2MD5(originalCode);
    }

    /**
     * 使用 Map按key进行排序
     * @param map
     * @return
     */
    public static Map<String, Object> sortMapByKey(Map<String, Object> map) {
        if (map == null || map.isEmpty()) {
            return null;
        }
        Map<String, Object> sortMap = new TreeMap<>(mapKeyComparator);
        sortMap.putAll(map);
        return sortMap;
    }

    public static class MapKeyComparator implements Comparator<String> {
        public int compare(String str1, String str2) {
            return str1.compareTo(str2);
        }
    }
}
